#include<sys/types.h>
#include<sys/stat.h>
#include<stdio.h>
#include<stdlib.h>
#include<errno.h>
#include<string.h>
#include<fcntl.h>
#include<unistd.h>
#include<dirent.h>

int ds18b20(float *tmp)
{ 
	int	      fd = -1;
	int           rv = -1;
	DIR	      *dp;
	struct dirent *direntp;
	int    	      found = 0;
	char          buf[100];
	char          temper_path[100] = "/sys/bus/w1/devices/";
	char          chip[30];
	char          *ptr = NULL;

    
	dp = opendir(temper_path);
    
	if(dp == NULL)
	{
      		//printf("open file error:%s\n",strerror(errno));
		return -1;

	}

	//printf("open file success,dp:%p\n",dp);

 	while((direntp=readdir(dp))  != NULL)
	{
	//	printf("%s\n",direntp->d_name);
		if ((strstr(direntp->d_name,"28")))
		{
			strcpy(chip, direntp->d_name);
			//   printf("found:%d\n",found);
			found = 1;
			//   printf("found=%d\n",found);
		}
	}	
	closedir(dp);

	if (!found)
	{
	//	printf("Not found");
		return -2;
	} 
    
	strncat(temper_path,chip,sizeof(temper_path));
	strncat(temper_path,"/w1_slave",sizeof(temper_path)-1);

	fd = open(temper_path, O_RDONLY);

	if (fd < 0)
	{
	//	printf("open file %s error:%s\n",temper_path,strerror(errno));
		return -3;
	}

	rv = read(fd,buf,sizeof(buf));

	if (rv < 0)
	{
	//	printf("read error:%s\n",strerror(errno));    
		return -4;
	}

	close(fd);

	ptr = strstr(buf,"t=");

	if (ptr == NULL)
	{
	//	printf("read temperature error\n");
		return -5;
	}

	ptr+=2;

	*tmp = atof(ptr);
	*tmp = (*tmp/1000);


	return 1;

}


